package bible.sunflower.util.http;

import java.net.SocketTimeoutException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;
import org.dom4j.DocumentHelper;

import bible.sunflower.util.XMLUtil;

public class HttpClientHelper{
	
	 static Logger log = Logger.getLogger( HttpClientHelper.class );
	
	public static String sendHttpRequest(String requestUrl, Map<String, Object> params, String charset, String cookieStr, int connectionTimeout, int socketTimeout  ){
		DefaultHttpClient httpclient = new DefaultHttpClient();
		if( connectionTimeout > 0 ){
			 HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), connectionTimeout);
		 }
		 if( socketTimeout > 0 ){
			 HttpConnectionParams.setSoTimeout(httpclient.getParams(), socketTimeout);
		 }
		HttpPost httpost = null;
		try {		
		httpost = new HttpPost( requestUrl );
		if( charset == null || charset.length() == 0 ){
			charset = "UTF-8";
		}
		//设置header
		httpost.addHeader("connection","keep-alive");
		//httpost.addHeader("X_REQUESTED_WITH","XMLHttpRequest");
		httpost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + charset );
		httpost.addHeader("Cache-Control","no-cache");
		if( cookieStr != null && cookieStr.length() > 0 ){
			httpost.setHeader("Cookie", cookieStr );
		}
		
        
		if( params != null && params.size() > 0 ){
			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
			for( String key : params.keySet() ){
				paramList.add(new BasicNameValuePair( key, params.get(key).toString() ) ); 
			}
			httpost.setEntity(new UrlEncodedFormEntity(paramList, charset)); 
		}

		log.debug( "executing request " +  httpost.getURI() );
		
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpost, responseHandler);
        
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if( cookies != null && cookies.size() > 0 ){
        	for( Cookie cookie : cookies ){
        		System.out.println("cookie : " + cookie + ",domain: " + cookie.getDomain() + ",path: " + cookie.getPath() );
        		System.out.println("cookie : " + cookie.getName() + "," + cookie.getValue());
        		if( cookie.getName().equals("JSESSIONID")){
        			System.out.println("session id is " + cookie.getValue() );
        		}
        		System.out.println( "cookie : " + cookies.toString() );
        	}
        }
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        
        System.out.println("----------------------------------------");
        Map<String, Object> map = XMLUtil.Dom2Map( DocumentHelper.parseText( responseBody));
        String jsonStr = JSONObject.fromObject(map).toString();
        System.out.println( jsonStr );
        System.out.println("----------------------------------------");
	    } catch(Exception e){
	    	if( e instanceof HttpHostConnectException || e instanceof ConnectTimeoutException ){
	    		System.out.println("网络故障,请检查网络!");
	    	}else if( e instanceof SocketTimeoutException ){
	    		System.out.println("读取超时,请检查服务器!");
	    	}
	    	e.printStackTrace();
	    }finally {
	        httpclient.getConnectionManager().shutdown();
	    }
		return "";
	}
	
	public static void uploadFile(){
		
	}
	
}
